<template>
    <div>
        <!-- 筛选区域 -->
        <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-semibold">品类数据统计</h2>
            <div class="flex space-x-4">
                <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" :shortcuts="dateShortcuts" @change="fetchData" />
            </div>
        </div>

        <!-- 数据卡片 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <el-card shadow="hover" class="bg-blue-50">
                <div class="p-4">
                    <div class="text-gray-500 text-sm mb-2">总下载量</div>
                    <div class="text-2xl font-bold text-blue-600">{{ formatNumber(totalDownloads) }}</div>
                </div>
            </el-card>

            <el-card shadow="hover" class="bg-purple-50">
                <div class="p-4">
                    <div class="text-gray-500 text-sm mb-2">总收藏量</div>
                    <div class="text-2xl font-bold text-purple-600">{{ formatNumber(totalFavorites) }}</div>
                </div>
            </el-card>

            <el-card shadow="hover" class="bg-green-50">
                <div class="p-4">
                    <div class="text-gray-500 text-sm mb-2">最高下载品类</div>
                    <div class="text-2xl font-bold text-green-600">{{ topCategory.category }}</div>
                    <div class="text-sm text-gray-500 mt-1">{{ formatNumber(topCategory.downloads) }}次</div>
                </div>
            </el-card>

            <el-card shadow="hover" class="bg-orange-50">
                <div class="p-4">
                    <div class="text-gray-500 text-sm mb-2">最高收藏品类</div>
                    <div class="text-2xl font-bold text-orange-600">{{ topFavoriteCategory.category }}</div>
                    <div class="text-sm text-gray-500 mt-1">{{ formatNumber(topFavoriteCategory.favorites) }}次</div>
                </div>
            </el-card>
        </div>

        <!-- 图表区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
            <el-card shadow="hover">
                <div class="p-4">
                    <h3 class="text-lg font-semibold mb-4">各品类下载量对比</h3>
                    <div ref="downloadChart" class="h-80"></div>
                </div>
            </el-card>

            <el-card shadow="hover">
                <div class="p-4">
                    <h3 class="text-lg font-semibold mb-4">各品类收藏量对比</h3>
                    <div ref="favoriteChart" class="h-80"></div>
                </div>
            </el-card>
        </div>

        <!-- 数据表格 -->
        <el-card shadow="hover">
            <div class="p-4">
                <h3 class="text-lg font-semibold mb-4">详细数据</h3>
                <el-table :data="categoryData" stripe style="width: 100%">
                    <el-table-column prop="category" label="品类" width="180" />
                    <el-table-column prop="downloads" label="下载量" sortable>
                        <template #default="{ row }">
                            <span class="font-medium">{{ formatNumber(row.downloads) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="favorites" label="收藏量" sortable>
                        <template #default="{ row }">
                            <span class="font-medium">{{ formatNumber(row.favorites) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="conversion" label="转化率" sortable>
                        <template #default="{ row }">
                            <el-progress :percentage="row.conversion" :color="getConversionColor(row.conversion)" />
                        </template>
                    </el-table-column>
                    <!-- <el-table-column label="操作" width="120">
                        <template #default="{ row }">
                            <el-button type="primary" size="small" @click="viewCategoryDetail(row.category)">
                                详情
                            </el-button>
                        </template>
                    </el-table-column> -->
                </el-table>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

// 图表实例
const downloadChart = ref(null)
const favoriteChart = ref(null)
let downloadChartInstance = null
let favoriteChartInstance = null

// 数据
const dateRange = ref([getDate(-6), new Date()]) // 默认最近7天
const totalDownloads = ref(0)
const totalFavorites = ref(0)
const topCategory = ref({ category: '', downloads: 0 })
const topFavoriteCategory = ref({ category: '', favorites: 0 })
const categoryData = ref([])

// 日期快捷选项
const dateShortcuts = [
    {
        text: '最近7天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 6)
            return [start, end]
        }
    },
    {
        text: '最近30天',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setDate(start.getDate() - 29)
            return [start, end]
        }
    },
    {
        text: '本月',
        value: () => {
            const end = new Date()
            const start = new Date(end.getFullYear(), end.getMonth(), 1)
            return [start, end]
        }
    }
]

// 获取日期
function getDate(days) {
    const date = new Date()
    date.setDate(date.getDate() + days)
    return date
}

// 初始化图表
const initCharts = () => {
    // 销毁旧实例
    if (downloadChartInstance) downloadChartInstance.dispose()
    if (favoriteChartInstance) favoriteChartInstance.dispose()

    // 创建新实例
    downloadChartInstance = echarts.init(downloadChart.value)
    favoriteChartInstance = echarts.init(favoriteChart.value)

    // 品类数据
    const categories = categoryData.value.map(item => item.category)
    const downloads = categoryData.value.map(item => item.downloads)
    const favorites = categoryData.value.map(item => item.favorites)

    // 下载量图表配置
    const downloadOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: '{b}<br/>{a}: {c}'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: categories,
            axisLabel: {
                rotate: 30
            }
        },
        yAxis: {
            type: 'value',
            name: '下载量'
        },
        series: [{
            name: '下载量',
            type: 'bar',
            data: downloads,
            itemStyle: {
                color: '#3b82f6'
            },
            barWidth: '40%'
        }]
    }

    // 收藏量图表配置
    const favoriteOption = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: '{b}<br/>{a}: {c}'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: categories,
            axisLabel: {
                rotate: 30
            }
        },
        yAxis: {
            type: 'value',
            name: '收藏量'
        },
        series: [{
            name: '收藏量',
            type: 'bar',
            data: favorites,
            itemStyle: {
                color: '#8b5cf6'
            },
            barWidth: '40%'
        }]
    }

    downloadChartInstance.setOption(downloadOption)
    favoriteChartInstance.setOption(favoriteOption)
}

// 获取数据
const fetchData = () => {
    // 模拟数据 - 实际项目中替换为API调用
    const mockCategories = ['运动鞋', '靴子', '凉鞋', '乐福鞋', '高跟鞋', '帆布鞋', '拖鞋']

    categoryData.value = mockCategories.map(category => {
        const downloads = Math.floor(Math.random() * 5000) + 1000
        const favorites = Math.floor(Math.random() * 3000) + 500
        return {
            category,
            downloads,
            favorites,
            conversion: parseFloat(((favorites / downloads) * 100).toFixed(1))
        }
    })

    // 计算汇总数据
    totalDownloads.value = categoryData.value.reduce((sum, item) => sum + item.downloads, 0)
    totalFavorites.value = categoryData.value.reduce((sum, item) => sum + item.favorites, 0)

    // 找出最高下载和收藏的品类
    topCategory.value = categoryData.value.reduce((max, item) =>
        item.downloads > max.downloads ? item : max, { category: '', downloads: 0 })

    topFavoriteCategory.value = categoryData.value.reduce((max, item) =>
        item.favorites > max.favorites ? item : max, { category: '', favorites: 0 })

    // 初始化图表
    initCharts()
}

// 查看品类详情
const viewCategoryDetail = (category) => {
    console.log('查看品类详情:', category)
    // 这里可以跳转到品类详情页面或打开弹窗
}

// 格式化数字
const formatNumber = (num) => {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

// 获取转化率颜色
const getConversionColor = (rate) => {
    if (rate > 60) return '#10b981'
    if (rate > 50) return '#3b82f6'
    if (rate > 40) return '#f59e0b'
    return '#ef4444'
}

// 响应式调整图表大小
const handleResize = () => {
    if (downloadChartInstance) downloadChartInstance.resize()
    if (favoriteChartInstance) favoriteChartInstance.resize()
}

onMounted(() => {
    fetchData()
    window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
    if (downloadChartInstance) downloadChartInstance.dispose()
    if (favoriteChartInstance) favoriteChartInstance.dispose()
    window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* 自定义样式 */
.el-card {
    border-radius: 0.5rem;
}

.el-table {
    border-radius: 0.5rem;
    overflow: hidden;
}

.el-progress {
    width: 80%;
}
</style>